import React, { useState, useEffect } from 'react';
import { message, Space } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { connect, Dispatch } from 'umi';
import moment from 'moment';
import { PageContainer } from '@ant-design/pro-layout';
import ProCard from '@ant-design/pro-card';
import { TASK_INIT, TASK_LIST, TASK_DETAIL, TASK_UNMOUNT } from '@/actions/task';
import { AGrid, AButton } from '@/components/SelfComp';
import { ConnectState } from '@/models/connect';
import { DataItem } from '@/types/global';
import { TaskDetailItem, TaskItem } from '@/types/task';
import { getItemValue } from '@/utils/commons';
import { dateFormat } from '@/utils/utils';
import TaskListQueryForm from './components/TaskListQueryForm';
import ViewTaskDrawer from './components/ViewTaskDrawer';
import './list.less';


interface TaskListProps {
  dispatch: Dispatch;
  taskList: TaskItem[],
  total: number,
  loading: boolean;
  detailLoading: boolean;
  exportLoading: boolean;
  developerData: DataItem[];
  testerData: DataItem[];
  taskTypeData: DataItem[];
  taskStatusData: DataItem[];
  systemData: DataItem[];
}

const EMPTY: TaskItem = {
  cqId: '',
  cqCode: '',
  taskId: '',
  taskName: '',
  funcCode: '',
  startDate: '',
  endDate: '',
  developer: '',
  tester: '',
  status: '',
  systemCode: '',
  comment: '',
  actInstId: '',
  actTaskId: '',
}

const EMPTY_DETAIL: TaskDetailItem = {
  ...EMPTY,
  cqName: '',
  funcName: '',
  systemName: '',
  appCode: '',
  appName: '',
  clstCode: '',
  clstName: '',
  auditor: '',
  designer: ''
}

const TaskList: React.FC<TaskListProps> = (props) => {
  // 任务详情弹窗
  const [viewDrawerVisible, setViewDrawerVisible] = useState<boolean>(false);
  const [taskFormData, setTaskFormData] = useState<TaskDetailItem>(EMPTY_DETAIL);
  const [selectedRows, setSelectedRows] = useState<TaskItem[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [queryParam, setQueryParam] = useState<TaskItem>();
  // 默认为10
  const [pageSize, setPageSize] = useState<number>(10);
  // const [flag, setFlag] = useState<FlagEnum>('view');

  useEffect(() => {
    console.info('TaskList.useEffect');
    // 查询本页面需所有参数
    // 获取所属系统
    // 获取审核人列表
    const { dispatch } = props;
    dispatch(TASK_INIT({}));
    return () => {
      dispatch(TASK_UNMOUNT({}));
    }
  }, []);

  const columns: ColumnsType<TaskItem> = [
    {
      title: '任务名称',
      dataIndex: 'taskName',
      width: 150,
      ellipsis: true
    },
    {
      title: '需求编号',
      dataIndex: 'cqCode',
      width: 150
    },
    {
      title: '所属系统',
      dataIndex: 'systemCode',
      width: 100
    },
    {
      title: '交易功能码',
      dataIndex: 'funcCode',
      width: 120
    },
    {
      title: '开始时间',
      dataIndex: 'startDate',
      width: 120,
      render: (text: string, record: TaskItem, index: number) => startDateFormat(record)
    },
    {
      title: '结束时间',
      dataIndex: 'endDate',
      width: 120,
      render: (text: string, record: TaskItem, index: number) => endDateFormat(record)
    },
    {
      title: '开发人员',
      dataIndex: 'developer',
      width: 120,
    },
    {
      title: '测试人员',
      dataIndex: 'tester',
      width: 120,
    },
    {
      title: '任务状态',
      dataIndex: 'status',
      width: 120,
      render: (text: string, record: TaskItem, index: number) => commonStatusFunc(record)
    }
  ];

  /**
   * 表格中任务状态转换
   */
  const commonStatusFunc = (record: TaskItem) => {
    const { taskName } = record;
    // 没有任务名，则为CQ任务
    if (!taskName) {
      return cqTaskStatusFunc(record.status);
    }
    // 否则为交易开发任务
    return tradeTaskStatusFunc(record.status);
  }

  /**
   * 需求任务状态转换
   */
  const cqTaskStatusFunc = (status: string) => {
    if (status === '1') {
        return '主开录入详细信息';
    }
    if (status === '2') {
        return '设计录入文档信息';
    }
    if (status === '3') {
        return '主开分配交易';
    }
    if (status === '4') {
        return '任务完成';
    }
    return status;
  }

  /**
   * 交易任务状态转换
   */
  const tradeTaskStatusFunc = (status: string) => {
    const { taskStatusData } = props;
    const value = getItemValue(taskStatusData, status);
    return value;
  }

  const startDateFormat = (record: TaskItem) => {
    const { startDate } = record;
    // 20190101 --> 2019-01-01
    return dateFormat(startDate);
  }

  const endDateFormat = (record: TaskItem) => {
    const { endDate } = record;
    // 20190101 --> 2019-01-01
    return dateFormat(endDate);
  }

  /**
   * 分页查询系统参数信息
   * @param {*} pageNum 页码
   * @param {*} pageSize 每页记录条数
   */
  const fetchAllTask = (pageNum: number, pageSize: number, queryParam?: TaskItem) => {
    const { dispatch } = props;
    dispatch(TASK_LIST({
      ...queryParam,
      pageSize,
      pageNum
    }));
  }

  /**
   * 表单提交
   */
  const handleSubmitEx = (record: TaskItem) => {
    // console.info('TaskList.handleSubmitEx');
    // console.info(record);
    const queryParam = {
      ...record
    };
    // 查询条件保存起来，方便点击页码时使用
    // setState回调方法，保证先更新state
    setQueryParam(queryParam);
    fetchAllTask(1, pageSize, queryParam);
  }

  /**
   * 根据查询条件导出表格数据
   * @param {*} record 查询表单
   */
  const handleExportEx = () => {
    // 先判断表格是否有数据
    const { taskList } = props;
    const size = taskList.length;
    if (size === 0) {
      message.warn('请先查询数据，在导出！');
      return;
    }
    const { total } = props;
    if (total === 5000) {
      message.warning('导出数据总条数超过5000，请增加查询条件！');
      return;
    }
    // 下载文件
    message.success('导出成功');
  }

  /**
   * 页码改变的回调，参数是改变后的页码及每页条数
   * @param page 改变后的页码，上送服务器端
   * @param pageSize 每页数据条数
   */
  const onPageNumAndSizeChange = (page: number, pageSize: number) => {
    // console.log(page, pageSize);
    setPageSize(pageSize);
    fetchAllTask(page, pageSize, queryParam);
  };

  const setRowClassName = (record: TaskItem, _index: number): string => {
      // console.log(`第${index}行，数据为${JSON.stringify(record)}`);
      const now = new Date().getTime();
      const { endDate } = record;
      const tmp = moment(endDate).toDate().getTime();
      // console.log(`${now}, ${tmp}`);
      // 任务结束时间在今天之前就变红，警示
      if (now > tmp) {
          return 'clickRowStyl';
      }
      return '';
  }

  const openViewTaskDrawer = async () => {
    // 表格选中内容
    // console.info('openViewTaskDrawer');
    if (selectedRowKeys.length === 0) {
      message.warn('请先选择一条数据!');
      return;
    }
    if (selectedRowKeys.length > 1) {
      message.warn('只能选择一条数据!');
      return;
    }
    const taskId = selectedRowKeys[0];
    // console.info('taskId', taskId);
    const { dispatch } = props;
    const res = await dispatch(TASK_DETAIL({
      taskId
    }));
    if (res) {
      // const { selectedRows } = state;
      // const row = selectedRows[0];
      const { result } = res;
      const taskFormData = {
        ...result
      }
      setTaskFormData(taskFormData);
      setViewDrawerVisible(true);
    }
  }

  const closeViewDrawer = () => {
    setViewDrawerVisible(false);
  }

  const renderLeftButton = () => {
    const { exportLoading, detailLoading } = props;
    return (
      <>
        <AButton type='primary' code='view' pageCode='task-list' name='查看详细' onClick={openViewTaskDrawer} loading={detailLoading} />
        <AButton type='primary' code='export' pageCode='task-list' name='导出' onClick={handleExportEx} loading={exportLoading} />
      </>
    );
  }

  /**
   * 表格勾选回调函数
   * @param {*} rows 表格选中数据集合
   */
  const onSelectRow = (keys: React.Key[], rows: TaskItem[]) => {
    setSelectedRowKeys(keys);
    setSelectedRows(rows);
  };

  const code = 'task-list';
  const { taskList } = props;
  const { loading, total } = props;
  const { developerData, testerData, taskTypeData, taskStatusData, systemData } = props;
  const rowKey = (record: TaskItem) => record.taskId;
  const pkField = 'taskId';

  return (
    <PageContainer>
      <Space direction='vertical' size='middle' style={{ display: 'flex' }}>
        <ProCard title='查询条件' headerBordered >
          <TaskListQueryForm
            colon={false}
            loading={loading}
            developerData={developerData}
            testerData={testerData}
            systemData={systemData}
            taskTypeData={taskTypeData}
            taskStatusData={taskStatusData}
            onSubmit={handleSubmitEx}
          />
        </ProCard>
        <ProCard>
          <AGrid
            code={code}
            noActionColumn={true}
            renderLeftButton={renderLeftButton}
            columns={columns}
            rowKey={rowKey}
            pkField={pkField}
            dataSource={taskList}
            loading={loading}
            total={total}
            onSelectRow={onSelectRow}
            onPageNumAndSizeChange={onPageNumAndSizeChange}
            rowClassName={setRowClassName}
            scroll={{x:1200}}
          />
        </ProCard>
      </Space>
      {
        !viewDrawerVisible ? null :
        <ViewTaskDrawer
          drawerVisible={viewDrawerVisible}
          drawerTitle='任务详情'
          drawerWidth={1000}
          colon={false}
          loading={false}
          formData={taskFormData}
          taskStatusData={taskStatusData}
          onHandlerCancel={closeViewDrawer}
        />
      }
    </PageContainer>
  );
}

export default connect((state: ConnectState) => ({
  taskList: state.tasks.rows,
  total: state.tasks.total,
  pageSize: state.tasks.pageSize,
  developerData: state.users.developerData,
  testerData: state.users.testerData,
  taskTypeData: state.systems.taskTypeData,
  taskStatusData: state.systems.taskStatusData,
  systemData: state.systems.systemData,
  loading: state.loading.effects['tasks/fetchAllTask'],
  detailLoading: state.loading.effects['tasks/fetchTaskDetail'],
  exportLoading: state.loading.effects['users/fetchRolesByUser'],
}))(TaskList);